package com.samxcode.leetcode;

/**
 * Write a function to find the longest common prefix string amongst an array of strings.
 * 
 * @author Sam
 *
 */
public class LongestCommonPrefix {

    public static void main(String[] args) {
        String[] ss = { "1234", "12345" };
        System.out.println(longestCommonPrefix(ss));
    }


    public static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder(strs[0].length());
        char c;
        for (int i = 0; i < strs[0].length(); i++) {
            c = strs[0].charAt(i);
            for (String str : strs) {
                if (str.length() < i + 1 || c != str.charAt(i)) {
                    return sb.toString();
                }
            }
            sb.append(c);
        }
        return sb.toString();
    }
}
